package com.lzx.java.smack.concurrent;

import static org.junit.Assert.*;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class CountDownLatchTest {

	@Test
	public void test1() throws InterruptedException {
		int size = 5;
		CountDownLatch countDownLatch = new CountDownLatch(size);
		System.out.println("main thread start...");
		// 启动只线程
		for (int i = 0; i < size; i++) {
			new Thread(new MyThread(countDownLatch)).start();
		}

		countDownLatch.await();
		System.out.println("main thread end...");

	}

	@Test
	public void test2() throws InterruptedException {
		int size = 5;
		CountDownLatch countDownLatch = new CountDownLatch(size);
		System.out.println("main thread start...");
		// 启动只线程
		for (int i = 0; i < size; i++) {
			new Thread(new MyThread(countDownLatch)).start();
		}

		countDownLatch.await(2, TimeUnit.SECONDS);
		System.out.println("main thread end...");

	}

	private class MyThread implements Runnable {
		CountDownLatch countDownLatch;

		public MyThread(CountDownLatch countDownLatch) {
			this.countDownLatch = countDownLatch;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				System.out.println("run thread:"
						+ Thread.currentThread().getName());
			} finally {
				countDownLatch.countDown();
			}

		}

	}

}
